import os
from selenium import webdriver
import time

with open("rename.js", "r+", encoding='utf-8')as f:
    rename_js = f.read()

log_file_name = "record.v2.log"

def get_text_from_baidu():
    d = webdriver.Chrome(executable_path=r"C:\Program Files\Google\Chrome\Application\chromedriver.exe")
    d.get("https://www.baidu.com")

    list_txt = []
    print("Working", end="")
    while True:
        print(".", end="")
        d.execute_script(rename_js)
        time.sleep(1)
        list_ele = d.find_elements_by_css_selector(".hotsearch-item.odd")
        list_ele += d.find_elements_by_css_selector(".hotsearch-item.even")
        if list_txt.count(list_ele[0].text) > 0:
            print("本次共有 %d 个内容" % len(list_txt))
            break
        for ele in list_ele:
            list_txt.append(ele.text)
        d.find_elements_by_css_selector("#hotsearch-refresh-btn")[0].click()
    print("")
    d.close()
    return list_txt


def write_to_file(my_list: list, time_str: str):
    if os.path.isfile(log_file_name) is False:
        open(log_file_name, "w+", encoding='utf-8').close()

    with open(log_file_name, "a+", encoding='utf-8') as f:
        out_str = '"%s":"%s"' % (time_str, '=' * 20)
        f.write(out_str + '\n')
        print(out_str)
        for my_str in my_list:
            out_str = '"%s":"%s"' % (time_str, my_str)
            f.write(out_str + '\n')


def get_now_time_str():
    now_time = time.time()
    localtime = time.localtime(now_time)
    return "%d/%02d/%02d %02d:%02d" % (
        localtime.tm_year,
        localtime.tm_mon,
        localtime.tm_mday,
        localtime.tm_hour,
        localtime.tm_min
    )


def main():
    now_time = time.time()
    # next_time = now_time + (30 * 60)
    next_time = now_time
    while True:
        now_time = time.time()
        if now_time >= next_time:
            next_time = now_time + (30 * 60)
            time_str = get_now_time_str()
            list_text = get_text_from_baidu()
            write_to_file(my_list=list_text, time_str=time_str)
            os.system("run_git.bat")
            print(">>>>>>>>>>upload finished.<<<<<<<<<<")

        time.sleep(1)


if __name__ == '__main__':
    main()
